#include <clusnet/base/ThreadPool.h>
#include <clusnet/base/CountDownLatch.h>
#include <clusnet/base/Logging.h>
#include <clusnet/base/CurrentThread.h>

#include <functional>
#include <stdio.h>
#include <unistd.h>



void print()
{
    printf("tid=%d\n", clusnet::base::CurrentThread::tid());
}

void printString(const std::string& str)
{
    LOG(INFO) << str;
    usleep(1000000);
}

void test(int maxSize)
{
    LOG(WARNING) << "Test ThreadPool with max queue size = " << maxSize;
    clusnet::base::ThreadPool pool(maxSize, "MainThreadPool");
    pool.start(5);

    LOG(INFO) << "Adding";
    pool.run(print);
    pool.run(print);
    for (int i = 0; i < 100; ++i)
    {
        char buf[32];
        snprintf(buf, sizeof buf, "task %d", i);
        pool.run(std::bind(printString, std::string(buf)));
    }
    LOG(INFO) << "Done";

    clusnet::base::CountDownLatch latch(1);
    pool.run(std::bind(&clusnet::base::CountDownLatch::countDown, &latch));
    latch.wait();
    pool.stop();
}

int main()
{
    InitLogging();
    test(0);
    test(1);
    test(5);
    test(10);
    test(50);

    google::ShutdownGoogleLogging();
    return 0;
}
